import { useAuthStore } from '@/store'
import { getUrl } from '@/utils'

/**
 * 已登录、白名单不拦截
 * 否则，全都跳转到登录
 */
export function createRouterGuard() {
  const auth = useAuthStore()
  const whiteList = ['/pages/profile/index']

  let interceptArr = ['navigateTo', 'switchTab']

  interceptArr.map((item) => {
    uni.addInterceptor(item, {
      invoke(e) {
        const hasPermission = auth.isLogin || whiteList.includes(e.url)
        if (!hasPermission) {
          wx.showToast({
            title: '请重新登录',
            icon: 'none',
            duration: 2000,
          })
          setTimeout(() => {
            getUrl() // 将进入登陆页面的前一个页面存入
            uni.reLaunch({
              url: '/pages/login-verify/index',
            })
          }, 500)
          return false
        }
        return true
      },
      success(e) {
        console.log(e)
      },
      fail(err) {
        console.log(err)
      },
    })
  })
}
